package com.weasel.im.server.handler;

import com.weasel.im.common.builder.MessageBuilder;
import com.weasel.im.common.domain.IMSession;
import com.weasel.im.common.domain.Message;
import com.weasel.im.common.manager.IMSessionManager;
import com.weasel.im.common.manager.LeaveMessageCacheManager;
import com.weasel.im.common.manager.UserSessionRelationManager;
import io.netty.channel.Channel;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.List;

/**上线消息的处理类
 * Created by Dylan on 2015/12/3.
 */
public class OnlineMessageHandler extends MessageHandler {

    private final static Logger logger = LoggerFactory.getLogger(OnlineMessageHandler.class);

    public OnlineMessageHandler(IMSessionManager sessionManager, UserSessionRelationManager relationManager, LeaveMessageCacheManager leaveMessageCacheManager) {
        super(sessionManager, relationManager, leaveMessageCacheManager);
    }


    public void handler(Channel channel, Message message) {

        String username = message.getFrom();
        String sessionid = channel.id().asShortText();
        logger.info("[server] 收到用户{}上线通知", username);

        String _sessionid = relationManager.getSessionidByUsername(username);
        if(StringUtils.isNotBlank(_sessionid)){  //该用户已经在线，强制对方下线
            IMSession session = sessionManager.get(_sessionid);
            Channel _channel = session.getChannel();
            _channel.writeAndFlush(MessageBuilder.start().from("服务器提示").to(username).content("该用户在其他机器上线，请重新登录").build());
            _channel.disconnect();
        }

        sendLeaveWord(sessionid);  //发送留言

        relationManager.relation(username, sessionid);
    }

    /**
     * 发送留言
     * @param sessionid
     */
    private void sendLeaveWord(final String sessionid){

        if(null == leaveMessageCacheManager){
            return;
        }
        new Thread(new Runnable() {
            public void run() {
                try {
                    Thread.currentThread().sleep(2000);
                    String username = relationManager.getUsernameBySessionid(sessionid);
                    logger.info("[server] 检查用户{}是否有留言", username);
                    final List<Message> messages = leaveMessageCacheManager.getAndRemove(username);
                    if(!messages.isEmpty()){
                        String sessionid = relationManager.getSessionidByUsername(username);
                        IMSession session = sessionManager.get(sessionid);
                        Channel channel = session.getChannel();
                        for (Message message : messages){
                            channel.writeAndFlush(message);
                        }
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }

    public Message.Type handlerMessageType() {
        return Message.Type.ONLINE;
    }
}
